<template>
  <div>
    <div
        class="topSearch"
        style="margin-bottom: 10px; display: flex; justify-content: space-between"
    >
      <div>
        <!-- <span>仓库： <el-select size="small"
                              style="width: 250px" v-model="params.areaId" clearable>
                <el-option v-for="item in warehouseList" :label="item.areaName" :value="item.area"
                           :key="item.area"></el-option>
              </el-select></span> -->
        <span style="margin-left: 15px"
        >门店名称：<el-input
            size="small"
            style="width: 250px"
            v-model="params.storeName"
            clearable
        ></el-input
        ></span>

        <span style="margin-left: 15px">所属仓库：</span>
        <el-select
            clearable
            v-model="areaId"
            size="small"
            style="width: 200px"
            placeholder="请选择"
        >
          <el-option
              v-for="item in warehouseList"
              :key="item.area"
              :label="item.areaName"
              :value="item.area"
          />
        </el-select>

        <span style="margin-left: 15px">
          <el-button size="small" type="primary" @click="_search"
          >搜 索</el-button
          >
          <el-button size="small" type="info" @click="_reset">重 置</el-button>
        </span>
      </div>
      <div>
        <el-button size="small" type="primary" @click="_add"
        >新增赵一鸣增加单
        </el-button
        >
        <el-button type="primary" size="small" @click="getData('download')"
        ><i class="el-icon-download"></i>增加单财务报表下载
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table
          :data="multipleData"
          height="calc(100vh - 350px)"
          :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
          :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="storeName" label="店铺"></el-table-column>
        <el-table-column prop="areaName" label="仓库"></el-table-column>
        <el-table-column
            v-for="col in editableColumns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
        >
          <template v-slot:default="scope">
            <p @click="cellClick(scope.row, col.prop)">
              {{ scope.row[col.prop] }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="付款时间"></el-table-column>
        <el-table-column label="付款截图">
          <template v-slot:default="scope">
            <div style="display: flex">
              <el-image
                  v-for="(item, index) in scope.row.payProofList"
                  :key="index"
                  :src="host + item"
                  :preview-src-list="
                  scope.row.payProofList.map((img) => host + img)
                "
                  class="img-item"
                  fit="cover"
              >
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="凭证截图">
          <template v-slot:default="scope">
            <div style="display: flex">
              <el-image
                  v-for="(item, index) in scope.row.addImgList"
                  :key="index"
                  :src="host + item"
                  :preview-src-list="
                  scope.row.addImgList.map((img) => host + img)
                "
                  class="img-item"
                  fit="cover"
              >
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="payCard" label="付款账号"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-link
                style="
                color: #66b1ff;
                text-decoration: underline;
                margin-right: 10px;
              "
                @click="_edit(scope.row)"
            >编 辑
            </el-link>
            <el-link
                v-if="userName=='曹紫芳'||'admin'"
                style="
                color: #ce0e0f;
                text-decoration: underline;
                margin-right: 10px;
              "
                @click="_delete(scope.row)"
            >删 除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="padding: 20px 0"
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog
          :visible.sync="dialogAdd"
          :title="title"
          top="10px"
          height="calc(100vh - 350px)"
          style="overflow-y: auto"
          width="40%"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <span style="width: 50px">店名：</span>
              <el-input
                  size="small"
                  style="width: 280px"
                  v-model="data.storeName"
              ></el-input>
            </el-col>
            <el-col
                :span="12"
                style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <div>
                <span style="color: red; display: inline">*</span>出库仓库：
              </div>

              <el-select
                  clearable
                  size="small"
                  v-model="data.area"
                  :disabled="disabled"
                  style="width: 78%"
                  placeholder="请选择"
              >
                <el-option
                    v-for="item in warehouseList"
                    :key="item.area"
                    :label="item.areaName"
                    :value="item.area"
                />
              </el-select>
            </el-col>
          </el-row>
          <!--        -->
          <el-row>
            <el-col :span="12">
              <span>金额：</span>
              <el-input-number
                  v-model="data.money"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('bjdFee', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <span>报价单：</span>
              <el-input-number
                  v-model="data.bjdMoney"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('bjdFee', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <!--        -->

          <!--        -->
          <el-row>
            <el-col :span="12">
              <span style="width: 70px">付款账号：</span>
              <el-input
                  style="width: 280px"
                  size="small"
                  v-model="data.payCard"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <span style="width: 70px">付款日期：</span>
              <el-date-picker
                  v-model="data.payTime"
                  type="date"
                  size="small"
                  style="width: 280px"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
              >
              </el-date-picker>
            </el-col>
          </el-row>
        </div>
        <div style="margin-top: 15px">
          <el-row>
            <el-col :span="12">
              <span>付款图：</span>
              <el-upload
                  multiple
                  class="uploader-wrap"
                  :headers="headers"
                  :action="`${$apiHost}/common/fileImgUrl`"
                  :on-success="paySuc"
                  :show-file-list="false"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
                <template #tip>
                  <div class="img-wrap" style="display: flex">
                    <div v-for="(item, index) in payProofList">
                      <el-image
                          :key="index"
                          :src="host + item"
                          :preview-src-list="
                          payProofList.map((img) => host + img)
                        "
                          class="img-item"
                          fit="cover"
                      >
                      </el-image>
                      <div @click="deletePic(index)">
                        <el-icon name="delete"></el-icon>
                      </div>
                    </div>
                  </div>
                </template>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <span style="width: initial">凭证：</span>
              <div style="display: inline-block">
                <span style="color: gray; font-size: 12px"
                >(粘贴复制即可上传图片)</span
                >
                <div class="div" style="display: flex; align-items: center">
                  <div
                      v-for="(v, i) in voucherList"
                      style="
                      display: flex;
                      align-items: center;
                      margin-right: 10px;
                    "
                      :key="i"
                  >
                    <el-image
                        v-if="v"
                        :key="i"
                        style="width: 50px; height: 50px"
                        ref="preview"
                        :src="host + v"
                        :preview-src-list="[host + v]"
                    >
                    </el-image>
                    <div @click="deleteImgVouchers(i)" v-show="!editDetails">
                      <el-icon name="delete"></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <span slot="footer">
          <el-button @click="dialogAdd = false">取 消</el-button>
          <el-button type="primary" @click="_submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import * as XLSX from 'xlsx-js-style'
import {localStorageAsync} from '@/utils/public'
import {Message} from 'element-ui'
import axios from 'axios'

export default {
  name: 'yimingMultipleOrder',
  data() {
    return {
      editDetails: false,
      dialogAdd: false,
      disabled: false,
      title: '',
      date: '',
      areaId: '',
      num: 0,
      userName: "",
      currentPage: 1,
      usrName: "",
      total: 0,
      host: this.$imgHost,
      warehouseList: [],
      editableColumns: [
        {prop: 'money', label: '金额'},
        {prop: 'bjdMoney', label: '报价单'},
      ],
      data: {},
      editId: '',
      params: {
        storeName: '',
        areaId: '',
        pageNumber: 1,
        pageSize: 20,
      },
      orderImg: [],
      orderProofList: [],
      productData: [],
      payProofList: [],
      voucherList: [],
      multipleData: [],
    }
  },
  computed: {
    headers() {
      const token = this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      },
    },
  },
  created() {
    this.areaList()
    this.getData()
    document.addEventListener('paste', this.handlePaste)
    const {userName = []} = this.$quinn.getStorage("userData") || {};
    this.userName = userName
  },
  methods: {
    /**
     * 方法说明 下载报表
     * author: iceyHu
     * description:
     * @param{Array} targetData 被下载的全部数据
     * @return
     * @createTime: DATE_TIME
     */
    // downloadReport(targetData) {
    //   if (!targetData.length) return Message.warning('暂无可下载数据')
    //   const wb = XLSX.utils.book_new()
    //   let data = [
    //     ['增加单财务报表'],
    //     ['店铺', '金额', '报价单', '付款时间', '付款截屏', '付款账号'],
    //   ]
    //   targetData.forEach((el) => {
    //     console.log('el', el)
    //     data.push([
    //       el.storeName,
    //       el.money,
    //       el.bjdMoney,
    //       el.payTime,
    //       el.payProofStr,
    //       el.payCard,
    //     ])
    //   })

    //   // data[data.length + 1] = [info.storeName,`实付:${info.totalDisCount}`,`补贴:${info.totalDiffPrice}`,`总价:${info.totalAmount}`];
    //   const ws = XLSX.utils.aoa_to_sheet(data)
    //   ws['!cols'] = [
    //     { wpx: 100 }, // 第一列宽度为100单位
    //     { wpx: 100 },
    //     { wpx: 100 },
    //     { wpx: 100 },
    //     { wpx: 100 },
    //     { wpx: 100 },
    //   ]
    //   ws['A1'].s = {
    //     alignment: { horizontal: 'center' },
    //     font: { blod: true, color: { rgb: '000000' } },
    //     fill: { fgColor: { rgb: 'ff6a00' } },
    //   }
    //   ws['A1'].hpt = 140
    //   XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
    //   ws['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }]
    //   const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
    //   // 创建一个 Blob 对象
    //   const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
    //   // 使用 Blob 对象创建一个链接
    //   const link = document.createElement('a')
    //   link.href = URL.createObjectURL(blob)
    //   link.download = `增加单财务报表.xlsx`

    //   // 触发下载
    //   link.click()

    //   // 清理
    //   URL.revokeObjectURL(link.href)

    //   function s2ab(s) {
    //     const buf = new ArrayBuffer(s.length)
    //     const view = new Uint8Array(buf)
    //     for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    //     return buf
    //   }
    // },
    /**
     * 方法说明
     * author: iceyhu
     * description: 通过图片url将图片转为base64格式
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    getBase64Image(url) {
      const img = new Image()
      // 因为是网络资源所以会有图片跨域问题产生，此属性可以解决跨域问题，下文详解
      img.setAttribute('crossOrigin', 'anonymous')
      // 如果需要兼容ios，这两个顺序一定不能换，先设置crossOrigin后设置src
      img.src = url
      return new Promise((resolve, reject) => {
        img.onload = () => {
          //canvas基本配置
          const canvas = document.createElement('canvas')
          canvas.width = img.width
          canvas.height = img.height
          const ctx = canvas.getContext('2d')
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
          resolve({
            success: true,
            // canvas.toDataURL的方法将图片的绝对路径转换为base64编码
            base64: canvas.toDataURL(),
          })
        }
        img.onerror = () => {
          reject({success: false})
        }
      })
    },

    /**
     * 方法说明
     * author: iceyhu
     * description: 下载带有图片文件的报表
     * @param{Array} tableData 被下载的全部表格数据
     * @return
     * @createTime: DATE_TIME
     */
    async downloadReportWithImage(tableData) {
      console.log('tableData', tableData)
      if (!tableData.length) return Message.warning('暂无可下载数据')
      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('Sheet1')
      // 添加数据
      worksheet.addRow(['收银台财务报表'])
      worksheet.addRow([
        '门店名称',
        '仓库',
        '金额',
        '报价单金额',
        '付款截图',
        '凭证截图',
        '付款日期',
        '付款账号',
        '退款',
        '二次上门',
      ])

      for (const el of tableData) {
        const row = worksheet.addRow([
          el.storeName,
          el.areaName,
          el.money,
          el.bjdMoney,
          '', // el.payProofList
          '', // el.addImgList
          el.payTime,
          el.payCard,
          el.refund,
          el.secondVisit,
        ])

        const images = Array.isArray(el.payProofList)
            ? el.payProofList
            : el.payProofList
                ? [el.payProofList]
                : []

        const images1 = Array.isArray(el.addImgList)
            ? el.addImgList
            : el.addImgList
                ? [el.addImgList]
                : []

        const imageHeight = 80
        const imageWidth = 100
        // const gap = 10
        // let totalWidth = images.length * (imageWidth + gap)
        if (images.length > 0) {
          worksheet.getRow(row.number).height = imageHeight + 10
          console.log('images', images)
          for (let i = 0; i < images.length; i++) {
            try {
              const base64 = await this.getBase64Image('https://' + images[i])
              //  通过 base64  将图像添加到工作簿
              const imageId = workbook.addImage({
                base64: base64.base64,
                extension: 'png',
              })
              // worksheet.addImage(imageId, 'E5:H20')
              worksheet.addImage(imageId, {
                tl: {
                  col: 4 + i * 0.99, // 控制偏移列位置（让图片横向排列在一格里）
                  row: row.number - 1,
                },
                ext: {width: imageWidth, height: imageHeight},
              })
            } catch (err) {
              console.warn('图片插入失败:', 'https://' + images[i], err)
            }
          }
        }

        if (images1.length > 0) {
          worksheet.getRow(row.number).height = imageHeight + 10
          console.log('images1', images1)
          for (let i = 0; i < images1.length; i++) {
            try {
              const base64_01 = await this.getBase64Image(
                  'https://' + images1[i]
              )
              //  通过 base64  将图像添加到工作簿
              const imageId1 = workbook.addImage({
                base64: base64_01.base64,
                extension: 'png',
              })
              // worksheet.addImage(imageId, 'E5:H20')
              worksheet.addImage(imageId1, {
                tl: {
                  col: 5 + i * 0.99, // 控制偏移列位置（让图片横向排列在一格里）
                  row: row.number - 1,
                },
                ext: {width: imageWidth, height: imageHeight},
              })
            } catch (err) {
              console.warn('图片插入失败:', 'https://' + images1[i], err)
            }
          }
        }
      }
      // 合并单元格
      worksheet.mergeCells('A1:J1')
      // 自定义样式
      // worksheet.getCell('A1').fill = {
      //   type: 'pattern',
      //   pattern: 'solid',
      //   fgColor: { argb: 'FFFF00' },
      // }
      // worksheet.getCell('A1').font = { bold: true, color: { argb: 'FF0000' } }
      worksheet.getCell('A1').alignment = {horizontal: 'center'}

      // 设置列宽
      worksheet.getColumn(1).width = 20
      worksheet.getColumn(2).width = 20
      worksheet.getColumn(3).width = 20
      worksheet.getColumn(4).width = 20
      worksheet.getColumn(5).width = 50
      worksheet.getColumn(6).width = 50
      worksheet.getColumn(7).width = 20
      worksheet.getColumn(8).width = 20
      worksheet.getColumn(9).width = 20
      worksheet.getColumn(10).width = 20

      // 导出文件
      const buffer = await workbook.xlsx.writeBuffer()
      const blob = new Blob([buffer], {type: 'application/octet-stream'})
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = '收银台财务报表.xlsx'
      link.click()
    },
    /**
     * 方法说明 处理粘贴
     * author: iceyhu
     * description:
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    handlePaste(event) {
      console.log('event', event)
      // 只能编辑损坏明细
      if (this.editDetails) return
      // !this.editVouchers &&
      if (!this.dialogAdd) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    /**
     * 方法说明
     * author: iceyhu
     * description: 上传图片
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    uploadImage(imageFile) {
      console.log('imageFile', imageFile)
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
          .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: window.$quinn.getStorage('token'),
            },
          })
          .then((response) => {
            if (this.dialogAdd) {
              // 新增上传
              // if (this.isBill) {
              //   // 付款图
              this.voucherList.push(response.data.result[0])
              console.log('this.voucherList', this.voucherList)

              // } else if (this.isVoucher) {
              // 增加单凭证
              // this.changeVouchers2.push(response.data.result[0])
              // }
              // this.changeVouchersList.push('https://' + response.data.result[0]);
            }
            // if (this.editVouchers) {
            //   // 上传修改凭证
            //   this.editImg.push(response.data.result[0])
            //   // this.editImgList.push('https://' + response.data.result[0]);
            // }
          })
          .catch((error) => {
          })
    },
    deleteImgVouchers(i) {
      this.voucherList.splice(i, 1)
    },
    async _submit() {
      try {
        const apiMap = {
          新增: this.$api.financeAddZymAddOrder,
          编辑: this.$api.financeUpdateZymAddOrder,
        }

        const apiFunc = apiMap[this.title]
        if (!apiFunc) return
        let areaObj = {
          area: '',
          areaName: '',
        }
        if (this.warehouseList.length) {
          areaObj = this.warehouseList.find(
              (v) => v.areaName == this.data.areaName
          )
        }
        Object.assign(this.data, areaObj)
        console.log('this.data233', this.data)
        const subData = {
          ...this.data,
          payProofList: this.payProofList,
          addImgList: this.voucherList,
        }
        if (this.title == '编辑') subData.id = this.editId
        const resDate = await apiFunc(subData)
        if (resDate == 1) {
          this.$message.success(`${this.title}成功！`)
          this.dialogAdd = false
          this.getData()
        }
      } catch (err) {
        console.error('接口请求出错：', err)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    blurEvent(row, index, column) {
      row.isEditing[column] = false
      const payload = {
        id: row.id,
        [column]: row[column],
      }
      this.$api.financeUpdateZymAddOrder(payload).then((res) => {
        if (res == 1) {
          this.$message.success('修改成功！')
          this.getData()
        }
      })
    },
    cellClick(row, column) {
      //input编辑
      Object.keys(row.isEditing).forEach((key) => {
        row.isEditing[key] = false
      })
      // 取消
      row.isEditing[column] = true
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getData()
    },
    _search() {
      this.params.pageNumber = 1
      this.params.area = this.areaId
      this.getData()
    },
    _reset() {
      this.params = this.$options.data().params
      this.getData()
    },
    /**
     * 方法说明
     * author: iceyhu
     * description:
     * @param{String} dataPurpose 获取数据用途 [default||download]
     * @return
     * @createTime: DATE_TIME
     */
    async getData(dataPurpose = 'default') {
      if (dataPurpose == 'default') {
        const result = await localStorageAsync.removeItem('download')
        console.log('result', result)
        if (result == 'success') {
          this.$api.financeGetZymAddOrderList(this.params).then((res) => {
            res.data.map((el) => {
              el.isEditing = {}
              this.editableColumns.forEach((col) => {
                el.isEditing[col.prop] = false
              })
            })
            this.multipleData = res.data
            this.total = res.total
          })
        }
      } else if (dataPurpose == 'download') {
        const result = await localStorageAsync.setItem('download', true)
        if (result == 'success') {
          this.params.pageSize = 10000
          this.$api.financeGetZymAddOrderList(this.params).then((res) => {
            // console.log('GetZymAddOrderList', res)
            res.data.map((el) => {
              el.isEditing = {}
              this.editableColumns.forEach((col) => {
                el.isEditing[col.prop] = false
              })
            })
            this.downloadReportWithImage(res.data)
          })
        }
      }
      // const result = await localStorageAsync.setItem('download', true)
      // if (result == 'ok') {
      //   // const params = this.params
      //   this.$api.financeGetZymAddOrderList(this.params).then((res) => {
      //     res.data.map((el) => {
      //       el.isEditing = {}
      //       this.editableColumns.forEach((col) => {
      //         el.isEditing[col.prop] = false
      //       })
      //     })
      //     if (dataPurpose == 'default') {
      //       this.multipleData = res.data
      //       this.total = res.total
      //     } else if (dataPurpose == 'download') {
      //       // this.downloadReport(res.data)
      //       this.downloadReportWithImage(res.data)
      //     }
      //   })
      // }
    },

    _add() {
      this.dialogAdd = true
      this.title = '新增'
      this.data = []
      this.payProofList = []
      this.voucherList = []
      this.orderProofList = []
    },
    areaList() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.warehouseList = res
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    paySuc(res) {
      if (res.code == 200 && res.result) {
        if (this.payProofList) {
          this.payProofList.push(res.result[0])
        } else {
          this.payProofList = [res.result[0]]
        }
      }
    },
    deletePic(i) {
      this.payProofList.splice(i, 1)
    },
    changeNum(field, val) {
      if (!val) {
        this.$set(this.data, field, 0)
      }
    },
    _delete(e) {
      const data = {
        id: e.id,
      }
      this.$confirm('确认删除？')
          .then((_) => {
            this.$api.financeDeleteZymAddOrder(data).then((res) => {
              if (res == 1) {
                this.$message.success('删除成功！')
                this.getData()
              }
            })
          })
          .catch((_) => {
            return
          })
    },
    _edit(a) {
      const data = JSON.parse(JSON.stringify(a))
      this.dialogAdd = true
      this.editId = data.id
      this.title = '编辑'
      this.data = data
      this.$set(this.data, 'area', a.areaName) // 回显
      this.payProofList = data.payProofList
      this.voucherList = a.addImgList
    },
  },
}
</script>

<style scoped lang="less">
.el-row {
  margin-bottom: 20px;

  span {
    display: inline-block;
    width: 90px;
  }
}
</style>
